package org.example.wx.netty.Handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

@ChannelHandler.Sharable
public class RPCServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext cx, Object msg){

        ByteBuf inBuf = (ByteBuf)msg;
        System.out.println("Server received message " + inBuf.toString(CharsetUtil.UTF_8));
        cx.write(inBuf);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext cx){
        cx.writeAndFlush(Unpooled.EMPTY_BUFFER);
        //下面被注释掉的代码，会在telnet端口输入任何一个字母就结束channel链接。
//        cx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext cx, Throwable exception){
        exception.printStackTrace();
        cx.close();
    }

}
